import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { UserInfo, LocationInfo } from '@/types'
import { authApi, userApi } from '@/api'
import wsManager from '@/utils/websocket'

export const useUserStore = defineStore(
  'user',
  () => {
    // 状态
    const token = ref<string>('')
    const userInfo = ref<UserInfo | null>(null)
    const location = ref<LocationInfo | null>(null)

    // 计算属性
    const isLogin = computed(() => !!token.value && !!userInfo.value)
    const isVip = computed(() => userInfo.value?.memberLevel === 'vip')
    const dailyPostLimit = computed(() => {
      return isVip.value ? 10 : 2
    })
    const remainingPosts = computed(() => {
      if (!userInfo.value) return 0
      return dailyPostLimit.value - userInfo.value.dailyPostCount
    })

    /**
     * 初始化用户信息
     */
    const initUserInfo = async () => {
      if (token.value) {
        try {
          await fetchUserInfo()
          // 连接WebSocket
          wsManager.connect().catch(err => {
            console.error('WebSocket连接失败:', err)
          })
        } catch (err) {
          console.error('获取用户信息失败:', err)
        }
      }
    }

    /**
     * 微信登录
     */
    const wechatLogin = async () => {
      try {
        // 1. 获取微信登录code
        const loginRes = await new Promise<UniApp.LoginRes>((resolve, reject) => {
          uni.login({
            provider: 'weixin',
            success: resolve,
            fail: reject
          })
        })

        // 2. 获取用户信息
        const userInfoRes = await new Promise<any>((resolve, reject) => {
          uni.getUserProfile({
            desc: '用于完善用户资料',
            success: resolve,
            fail: reject
          })
        })

        // 3. 调用后端登录接口
        const res = await authApi.wechatLogin(loginRes.code, {
          nickName: userInfoRes.userInfo.nickName,
          avatarUrl: userInfoRes.userInfo.avatarUrl,
          gender: userInfoRes.userInfo.gender
        })

        // 4. 保存token和用户信息
        token.value = res.token
        userInfo.value = res.userInfo

        // 5. 连接WebSocket
        wsManager.connect().catch(err => {
          console.error('WebSocket连接失败:', err)
        })

        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })

        return true
      } catch (err: any) {
        console.error('登录失败:', err)
        uni.showToast({
          title: err.message || '登录失败',
          icon: 'none'
        })
        return false
      }
    }

    /**
     * 绑定手机号
     */
    const bindPhone = async (code: string) => {
      try {
        const res = await authApi.bindPhone(code)
        if (userInfo.value) {
          userInfo.value.phone = res.phone
        }
        uni.showToast({
          title: '绑定成功',
          icon: 'success'
        })
        return true
      } catch (err: any) {
        console.error('绑定手机号失败:', err)
        uni.showToast({
          title: err.message || '绑定失败',
          icon: 'none'
        })
        return false
      }
    }

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
      try {
        const res = await userApi.getProfile()
        userInfo.value = res
      } catch (err) {
        console.error('获取用户信息失败:', err)
        throw err
      }
    }

    /**
     * 更新用户信息
     */
    const updateUserInfo = async (data: Partial<UserInfo>) => {
      try {
        const res = await userApi.updateProfile(data)
        userInfo.value = res
        uni.showToast({
          title: '更新成功',
          icon: 'success'
        })
        return true
      } catch (err: any) {
        console.error('更新用户信息失败:', err)
        uni.showToast({
          title: err.message || '更新失败',
          icon: 'none'
        })
        return false
      }
    }

    /**
     * 获取位置信息
     */
    const getLocation = async () => {
      try {
        const res = await new Promise<UniApp.GetLocationSuccess>((resolve, reject) => {
          uni.getLocation({
            type: 'gcj02',
            success: resolve,
            fail: reject
          })
        })

        // 逆地理编码获取地址信息(需要调用地图API)
        // 这里简化处理,实际应该调用地图服务
        location.value = {
          province: '山东省',
          city: '菏泽市',
          district: '牡丹区',
          address: '',
          lat: res.latitude,
          lng: res.longitude
        }

        return location.value
      } catch (err) {
        console.error('获取位置失败:', err)
        uni.showToast({
          title: '获取位置失败',
          icon: 'none'
        })
        return null
      }
    }

    /**
     * 退出登录
     */
    const logout = () => {
      token.value = ''
      userInfo.value = null
      location.value = null

      // 关闭WebSocket
      wsManager.close()

      // 清除本地存储
      uni.clearStorageSync()

      uni.showToast({
        title: '已退出登录',
        icon: 'success'
      })
    }

    /**
     * 增加发布次数
     */
    const incrementPostCount = () => {
      if (userInfo.value) {
        userInfo.value.dailyPostCount++
      }
    }

    return {
      token,
      userInfo,
      location,
      isLogin,
      isVip,
      dailyPostLimit,
      remainingPosts,
      initUserInfo,
      wechatLogin,
      bindPhone,
      fetchUserInfo,
      updateUserInfo,
      getLocation,
      logout,
      incrementPostCount
    }
  },
  {
    persist: {
      paths: ['token', 'userInfo', 'location']
    }
  }
)
